package com.xxx.mall.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxx.mall.converter.SpuConverter;
import com.xxx.mall.dto.SpuAttrValueDTO;
import com.xxx.mall.mapper.SpuAttrValueMapper;
import com.xxx.mall.model.SpuAttrValue;
import com.xxx.mall.service.SpuAttrValueService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商品规格属性关联信息 服务实现类
 * </p>
 *
 * @author 邢晨旭
 * @since 2023-11-24
 */
@Service
public class SpuAttrValueServiceImpl extends ServiceImpl<SpuAttrValueMapper, SpuAttrValue> implements SpuAttrValueService {

    @Resource
    SpuConverter spuConverter;

    @Override
    public void updateSpuAttr(Long spuId, List<SpuAttrValueDTO> spuAttrValues) {
        //查询历史数据
        List<Long> dbIds = baseMapper.queryIdsBySpuId(spuId);
        List<SpuAttrValue> updateList = new ArrayList<>();
        List<SpuAttrValue> saveList = new ArrayList<>();
        spuAttrValues.forEach(item -> {
            SpuAttrValue spuAttrValue = spuConverter.toSpuAttrValue(item);
            spuAttrValue.setSpuId(spuId);
            if (item.getSpuAttrValueId() == null) {
                saveList.add(spuAttrValue);
            } else {
                if (dbIds.contains(item.getSpuAttrValueId())) {
                    //修改
                    updateList.add(spuAttrValue);
                }
                dbIds.remove(item.getSpuAttrValueId());
            }

        });
        //新增
        if (CollUtil.isNotEmpty(saveList)) {
            baseMapper.saveBatch(saveList);
        }
        //修改
        if (CollUtil.isNotEmpty(updateList)) {
            baseMapper.updateBatch(updateList);
        }
        //删除
        if (CollUtil.isNotEmpty(dbIds)) {
            baseMapper.removeBatchByIds(dbIds);
        }

    }
}
